//go:build ignore
// +build ignore

// This program generates oslist.go. It can be invoked by running
// go generate
package main

import (
	"bufio"
	"bytes"
	"log"
	"os"
	"os/exec"
	"sort"
	"strings"
	"text/template"
	"time"
)

func main() {
	out, err := exec.Command("go", "tool", "dist", "list").Output()
	die(err)

	sc := bufio.NewScanner(bytes.NewReader(out))
	osmap := make(map[string]bool)
	archmap := make(map[string]bool)

	for sc.Scan() {
		parts := strings.Split(sc.Text(), "/")
		if _, ok := osmap[parts[0]]; !ok {
			osmap[parts[0]] = true
		}
		if _, ok := archmap[parts[1]]; !ok {
			archmap[parts[1]] = true
		}
	}
	die(sc.Err())

	f, err := os.Create("oslist.go")
	die(err)
	defer f.Close()

	oslist := make([]string, len(osmap))
	archlist := make([]string, len(archmap))

	i := 0
	for k := range osmap {
		oslist[i] = k
		i++
	}
	i = 0
	for k := range archmap {
		archlist[i] = k
		i++
	}

	// Make the output deterministic because iteration order over Go map keys
	// is random.
	sort.Strings(oslist)
	sort.Strings(archlist)

	packageTemplate.Execute(f, struct {
		Timestamp time.Time
		OS        []string
		Arch      []string
	}{
		Timestamp: time.Now(),
		OS:        oslist,
		Arch:      archlist,
	})
}

func die(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

var packageTemplate = template.Must(template.New("").Parse(`// Code generated by go generate; DO NOT EDIT.
// This file was generated by robots at
// {{ .Timestamp }}
// using data from 'go tool dist list'
package util

var validOS = map[string]bool{
{{- range .OS }}
	{{ printf "%q: true" . }},
{{- end }}
}
var validArch = map[string]bool{
{{- range .Arch }}
	{{ printf "%q: true" . }},
{{- end }}
}
`))
